import bpy

from . import (render,
               asset,
               )

mod_tuple = (
    render,
    asset,
)


def test_port(port: int):
    import socket
    import errno

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ret = False
    try:
        s.bind(("127.0.0.1", port))
    except socket.error as e:
        if e.errno == errno.EADDRINUSE:
            print(f"{port}\tPort is already in use")
            ret = True

    s.close()

    return ret


def get_port(port: int):
    from time import time
    st = time()

    while True:
        ti = time() - st
        if test_port(port):
            print(f'find {port} in time {ti}')
            return port

        if ti > 10:
            return

        port += 1


def show_docs(self, context):
    import os
    import sys
    import subprocess

    if not getattr(self.__class__, 'available_port', False):
        self.__class__.available_port = get_port(1024)
    available_port = self.__class__.available_port

    exec_py = sys.executable
    exec_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "docs")  # point to cur_dir/index.html
    cmd = f'\'{exec_py}\' -m http.server --directory "{exec_dir}" {available_port}'

    subprocess.Popen(cmd, shell=True)
    bpy.ops.wm.url_open(url=f'http://localhost:{available_port}')
    return {'FINISHED'}


SHOW_DOCS = type("test",
                 (bpy.types.Operator,),
                 {"execute": show_docs,
                  "bl_idname": "render_master.show_doc",
                  "bl_label": "打开文档",
                  }
                 )


def register():
    for i in mod_tuple:
        i.register()
    # bpy.utils.register_class(SHOW_DOCS) #TODO


def unregister():
    for i in mod_tuple:
        i.unregister()
    # bpy.utils.unregister_class(SHOW_DOCS)
